<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>数组拷贝的方法 | 谦谦君子</title>
  <meta name="keywords" content=" 面试 , 前端 ">
  <meta name="description" content="数组拷贝的方法 | 谦谦君子">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="description" content="谦谦君子的个人博客,谦谦君子，湛礼桂">
<meta property="og:type" content="website">
<meta property="og:title" content="about">
<meta property="og:url" content="https://zhanligui.gitee.io/about/index.html">
<meta property="og:site_name" content="谦谦君子">
<meta property="og:description" content="谦谦君子的个人博客,谦谦君子，湛礼桂">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-10-21T09:27:05.000Z">
<meta property="article:modified_time" content="2021-12-06T06:50:36.883Z">
<meta property="article:author" content="谦谦君子">
<meta property="article:tag" content="谦谦君子的个人博客,谦谦君子，湛礼桂">
<meta name="twitter:card" content="summary">


<link rel="icon" href="/img/avatar.jpg">

<link href="/css/style.css?v=1.1.0" rel="stylesheet">

<link href="/css/hl_theme/atom-light.css?v=1.1.0" rel="stylesheet">

<link href="//cdn.jsdelivr.net/npm/animate.css@4.1.0/animate.min.css" rel="stylesheet">

<script src="//cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js"></script>
<script src="/js/titleTip.js?v=1.1.0" ></script>

<script src="//cdn.jsdelivr.net/npm/highlightjs@9.16.2/highlight.pack.min.js"></script>
<script>
    hljs.initHighlightingOnLoad();
</script>

<script src="//cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.min.js"></script>



<script src="//cdn.jsdelivr.net/npm/jquery.cookie@1.4.1/jquery.cookie.min.js" ></script>

<script src="/js/iconfont.js?v=1.1.0" ></script>

<meta name="generator" content="Hexo 5.2.0"></head>
<div style="display: none">
  <input class="theme_disqus_on" value="false">
  <input class="theme_preload_comment" value="">
  <input class="theme_blog_path" value="">
  <input id="theme_shortcut" value="true" />
  <input id="theme_highlight_on" value="true" />
  <input id="theme_code_copy" value="true" />
</div>



<body>
<aside class="nav">
    <div class="nav-left">
        <a href="/"
   class="avatar_target">
    <img class="avatar"
         src="/img/avatar.jpg"/>
</a>
<div class="author">
    <span>谦谦君子</span>
</div>

<div class="icon">
    
        
            <a title="rss"
               href="/atom.xml"
               target="_blank">
                
                    <svg class="iconfont-svg" aria-hidden="true">
                        <use xlink:href="#icon-rss"></use>
                    </svg>
                
            </a>
        
    
        
            <a title="github"
               href="https://github.com/yelog"
               target="_blank">
                
                    <svg class="iconfont-svg" aria-hidden="true">
                        <use xlink:href="#icon-github"></use>
                    </svg>
                
            </a>
        
    
        
            <a title="facebook"
               href="https://www.facebook.com/faker.tops"
               target="_blank">
                
                    <svg class="iconfont-svg" aria-hidden="true">
                        <use xlink:href="#icon-facebook"></use>
                    </svg>
                
            </a>
        
    
        
    
        
    
        
            <a title="instagram"
               href="https://www.facebook.com/faker.tops"
               target="_blank">
                
                    <svg class="iconfont-svg" aria-hidden="true">
                        <use xlink:href="#icon-instagram"></use>
                    </svg>
                
            </a>
        
    
        
            <a title="reddit"
               href="https://www.reddit.com/user/yelog/"
               target="_blank">
                
                    <svg class="iconfont-svg" aria-hidden="true">
                        <use xlink:href="#icon-reddit"></use>
                    </svg>
                
            </a>
        
    
        
            <a title="weibo"
               href="http://weibo.com/u/2307534817"
               target="_blank">
                
                    <svg class="iconfont-svg" aria-hidden="true">
                        <use xlink:href="#icon-weibo"></use>
                    </svg>
                
            </a>
        
    
        
            <a title="jianshu"
               href="https://www.jianshu.com/u/ff56736de7cf"
               target="_blank">
                
                    <svg class="iconfont-svg" aria-hidden="true">
                        <use xlink:href="#icon-jianshu"></use>
                    </svg>
                
            </a>
        
    
        
            <a title="zhihu"
               href="https://www.zhihu.com/people/jaytp/activities"
               target="_blank">
                
                    <svg class="iconfont-svg" aria-hidden="true">
                        <use xlink:href="#icon-zhihu"></use>
                    </svg>
                
            </a>
        
    
        
    
        
            <a title="oschina"
               href="https://my.oschina.net/yelog"
               target="_blank">
                
                    <svg class="iconfont-svg" aria-hidden="true">
                        <use xlink:href="#icon-oschina"></use>
                    </svg>
                
            </a>
        
    
        
    
        
            <a title="email"
               href="mailto:jaytp@qq.com"
               target="_blank">
                
                    <svg class="iconfont-svg" aria-hidden="true">
                        <use xlink:href="#icon-email"></use>
                    </svg>
                
            </a>
        
    
        
            <a title="qq"
               href="http://wpa.qq.com/msgrd?v=3&uin=872336115&site=qq&menu=yes"
               target="_blank">
                
                    <svg class="iconfont-svg" aria-hidden="true">
                        <use xlink:href="#icon-qq"></use>
                    </svg>
                
            </a>
        
    
        
            <a title="kugou"
               href="https://www.kugou.com/"
               target="_blank">
                
                    <svg class="iconfont-svg" aria-hidden="true">
                        <use xlink:href="#icon-kugou"></use>
                    </svg>
                
            </a>
        
    
        
            <a title="neteasemusic"
               href="https://music.163.com/#/user/home?id=88151013"
               target="_blank">
                
                    <svg class="iconfont-svg" aria-hidden="true">
                        <use xlink:href="#icon-neteasemusic"></use>
                    </svg>
                
            </a>
        
    
</div>




<ul>
    <li>
        <div class="all active" data-rel="全部文章">全部文章
            
                <small>(16)</small>
            
        </div>
    </li>
    
        
            
                <li>
                    <div data-rel="技巧">
                        
                        技巧
                        <small>(2)</small>
                        
                    </div>
                    
                </li>
            
        
    
        
            
                <li>
                    <div data-rel="面试">
                        
                        面试
                        <small>(3)</small>
                        
                    </div>
                    
                </li>
            
        
    
        
            
                <li>
                    <div data-rel="日记">
                        
                        日记
                        <small>(1)</small>
                        
                    </div>
                    
                </li>
            
        
    
        
            
                <li>
                    <div data-rel="项目文档">
                        
                        项目文档
                        <small>(6)</small>
                        
                    </div>
                    
                </li>
            
        
    
        
            
                <li>
                    <div data-rel="hexo">
                        
                        hexo
                        <small>(2)</small>
                        
                    </div>
                    
                </li>
            
        
    
</ul>
<div class="left-bottom">
    <div class="menus">
        
            
            
            
    </div>
    <div>
        
            <a class="about  hasFriend  site_url"
               
               href="/about">关于</a>
        
        <a style="width: 50%"
                
                                           class="friends">友链</a>
        
    </div>
</div>
<input type="hidden" id="yelog_site_posts_number" value="16">

<div style="display: none">
    <span id="busuanzi_value_site_uv"></span>
    <span id="busuanzi_value_site_pv"></span>
</div>

    </div>
    <div class="nav-right">
        <div class="friends-area">
    <div class="friends-title">
        友情链接
        <i class="iconfont icon-left"></i>
    </div>
    <div class="friends-content">
        <ul>
            
            <li><a target="_blank" href="http://yelog.org/">叶落阁</a></li>
            
        </ul>
    </div>
</div>
        <div class="title-list">
    <div class="right-top">
        <div id="default-panel">
            <i class="iconfont icon-search" data-title="搜索 快捷键 i"></i>
            <div class="right-title">全部文章</div>
            <i class="iconfont icon-file-tree" data-title="切换到大纲视图 快捷键 w"></i>
        </div>
        <div id="search-panel">
            <i class="iconfont icon-left" data-title="返回"></i>
            <input id="local-search-input" autocomplete="off"/>
            <label class="border-line" for="input"></label>
            <i class="iconfont icon-case-sensitive" data-title="大小写敏感"></i>
            <i class="iconfont icon-tag" data-title="标签"></i>
        </div>
        <div id="outline-panel" style="display: none">
            <div class="right-title">大纲</div>
            <i class="iconfont icon-list" data-title="切换到文章列表"></i>
        </div>
    </div>

    <div class="tags-list">
    <input id="tag-search" />
    <div class="tag-wrapper">
        
            <li class="article-tag-list-item">
                <i class="iconfont icon-tag"></i><a>技巧</a>
            </li>
        
            <li class="article-tag-list-item">
                <i class="iconfont icon-tag"></i><a>面试</a>
            </li>
        
            <li class="article-tag-list-item">
                <i class="iconfont icon-tag"></i><a>前端</a>
            </li>
        
            <li class="article-tag-list-item">
                <i class="iconfont icon-tag"></i><a>日记</a>
            </li>
        
            <li class="article-tag-list-item">
                <i class="iconfont icon-tag"></i><a>探花交友</a>
            </li>
        
            <li class="article-tag-list-item">
                <i class="iconfont icon-tag"></i><a>项目</a>
            </li>
        
            <li class="article-tag-list-item">
                <i class="iconfont icon-tag"></i><a>hexo</a>
            </li>
        
    </div>

</div>

    
    <nav id="title-list-nav">
        
        <a  class="全部文章 "
           href="/posts/55136.html"
           data-tag=""
           data-author="" >
            <span class="post-title" title="vue3">vue3</span>
            <span class="post-date" title="2021-12-07 10:07:53">2021/12/07</span>
        </a>
        
        <a  class="全部文章 "
           href="/posts/16107.html"
           data-tag=""
           data-author="" >
            <span class="post-title" title="Hello World">Hello World</span>
            <span class="post-date" title="2021-12-06 14:50:36">2021/12/06</span>
        </a>
        
        <a  class="全部文章 项目文档 "
           href="/posts/10003.html"
           data-tag="探花交友,项目"
           data-author="" >
            <span class="post-title" title="第三章 React-native - 基础">第三章 React-native - 基础</span>
            <span class="post-date" title="2020-11-11 11:11:11">2020/11/11</span>
        </a>
        
        <a  class="全部文章 项目文档 "
           href="/posts/10002.html"
           data-tag="探花交友,项目"
           data-author="" >
            <span class="post-title" title="第二章 探花交友 - 环境搭建">第二章 探花交友 - 环境搭建</span>
            <span class="post-date" title="2020-11-11 11:11:11">2020/11/11</span>
        </a>
        
        <a  class="全部文章 项目文档 "
           href="/posts/10001.html"
           data-tag="探花交友,项目"
           data-author="" >
            <span class="post-title" title="第一章 探花交友 - Android   课程安排">第一章 探花交友 - Android   课程安排</span>
            <span class="post-date" title="2020-11-11 11:11:11">2020/11/11</span>
        </a>
        
        <a  class="全部文章 项目文档 "
           href="/posts/10000.html"
           data-tag="探花交友,项目"
           data-author="" >
            <span class="post-title" title="探花交友-概述">探花交友-概述</span>
            <span class="post-date" title="2020-11-11 11:11:11">2020/11/11</span>
        </a>
        
        <a  class="全部文章 项目文档 "
           href="/posts/10005.html"
           data-tag="探花交友,项目"
           data-author="" >
            <span class="post-title" title="探花交友-插件">探花交友-插件</span>
            <span class="post-date" title="2020-11-11 11:11:11">2020/11/11</span>
        </a>
        
        <a  class="全部文章 项目文档 "
           href="/posts/10004.html"
           data-tag="探花交友,项目"
           data-author="" >
            <span class="post-title" title="第四章 探花交友 - 项目接口文档">第四章 探花交友 - 项目接口文档</span>
            <span class="post-date" title="2020-11-11 11:11:11">2020/11/11</span>
        </a>
        
        <a  class="全部文章 hexo "
           href="/posts/49579.html"
           data-tag="hexo"
           data-author="" >
            <span class="post-title" title="Hexo 加入字数统计 WordCount">Hexo 加入字数统计 WordCount</span>
            <span class="post-date" title="2020-11-04 17:20:29">2020/11/04</span>
        </a>
        
        <a  class="全部文章 hexo "
           href="/posts/21358.html"
           data-tag="hexo"
           data-author="" >
            <span class="post-title" title="生成永久链接(permalink) | hexo">生成永久链接(permalink) | hexo</span>
            <span class="post-date" title="2020-11-04 17:20:29">2020/11/04</span>
        </a>
        
        <a  class="全部文章 技巧 "
           href="/posts/60475.html"
           data-tag="技巧"
           data-author="" >
            <span class="post-title" title="思否免登陆复制方法">思否免登陆复制方法</span>
            <span class="post-date" title="2020-11-04 15:24:21">2020/11/04</span>
        </a>
        
        <a  class="全部文章 技巧 "
           href="/posts/64216.html"
           data-tag="技巧"
           data-author="" >
            <span class="post-title" title="网页可随意编辑">网页可随意编辑</span>
            <span class="post-date" title="2020-11-04 15:24:21">2020/11/04</span>
        </a>
        
        <a  class="全部文章 面试 "
           href="/posts/7266.html"
           data-tag="面试,前端"
           data-author="" >
            <span class="post-title" title="数组拷贝的方法">数组拷贝的方法</span>
            <span class="post-date" title="2020-11-04 15:24:21">2020/11/04</span>
        </a>
        
        <a  class="全部文章 面试 "
           href="/posts/53209.html"
           data-tag="面试,前端"
           data-author="" >
            <span class="post-title" title="网络协议">网络协议</span>
            <span class="post-date" title="2020-11-02 11:08:31">2020/11/02</span>
        </a>
        
        <a  class="全部文章 面试 "
           href="/posts/43383.html"
           data-tag="面试,前端"
           data-author="" >
            <span class="post-title" title="强缓存和协商缓存">强缓存和协商缓存</span>
            <span class="post-date" title="2020-10-30 14:26:59">2020/10/30</span>
        </a>
        
        <a  class="全部文章 日记 "
           href="/posts/58040.html"
           data-tag="日记"
           data-author="" >
            <span class="post-title" title="今日来了一只不速之客">今日来了一只不速之客</span>
            <span class="post-date" title="2020-10-23 17:39:09">2020/10/23</span>
        </a>
        
        <div id="no-item-tips">

        </div>
    </nav>
    <div id="outline-list">
    </div>
</div>

    </div>
    <div class="hide-list">
        <div class="semicircle" data-title="切换全屏 快捷键 s">
            <div class="brackets first"><</div>
            <div class="brackets">&gt;</div>
        </div>
    </div>
</aside>
<div id="post">
    <div class="pjax">
        <article id="post-面试/数组拷贝的方法" class="article article-type-post" itemscope itemprop="blogPost">
    
        <h1 class="article-title">数组拷贝的方法</h1>
    
    <div class="article-meta">
        
        
        
        <span class="book">
            <i class="iconfont icon-category"></i>
            
            
            <a  data-rel="面试">面试</a>
            
        </span>
        
        
        <span class="tag">
            <i class="iconfont icon-tag"></i>
            
            <a class="color3">面试</a>
            
            <a class="color3">前端</a>
            
        </span>
        
    </div>
    <div class="article-meta">
        
            发布时间 : <time class="date" title='最后更新: 2021-12-06 14:50:36'>2020-11-04 15:24</time>
        
    </div>
    <div class="article-meta">
        
        
        <span id="busuanzi_container_page_pv">
            阅读 :<span id="busuanzi_value_page_pv">
                <span class="count-comment">
                    <span class="spinner">
                      <div class="cube1"></div>
                      <div class="cube2"></div>
                    </span>
                </span>
            </span>
        </span>
        
        
    </div>
    
    <div class="toc-ref">
    
        <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#JavaScript%E4%B8%AD%E5%8D%81%E7%A7%8D%E4%B8%80%E6%AD%A5%E6%8B%B7%E8%B4%9D%E6%95%B0%E7%BB%84%E7%9A%84%E6%96%B9%E6%B3%95"><span class="toc-text">JavaScript中十种一步拷贝数组的方法</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%E3%80%81%E6%89%A9%E5%B1%95%E8%BF%90%E7%AE%97%E7%AC%A6%EF%BC%88%E6%B5%85%E6%8B%B7%E8%B4%9D%EF%BC%89"><span class="toc-text">1、扩展运算符（浅拷贝）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2%E3%80%81for-%E5%BE%AA%E7%8E%AF%EF%BC%88%E6%B5%85%E6%8B%B7%E8%B4%9D%EF%BC%89"><span class="toc-text">2、for()循环（浅拷贝）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3%E3%80%81while-%E5%BE%AA%E7%8E%AF%EF%BC%88%E6%B5%85%E6%8B%B7%E8%B4%9D%EF%BC%89"><span class="toc-text">3、while()循环（浅拷贝）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4%E3%80%81Array-map%EF%BC%88%E6%B5%85%E6%8B%B7%E8%B4%9D%EF%BC%89"><span class="toc-text">4、Array.map（浅拷贝）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5%E3%80%81Array-filter%EF%BC%88%E6%B5%85%E6%8B%B7%E8%B4%9D%EF%BC%89"><span class="toc-text">5、Array.filter（浅拷贝）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6%E3%80%81Array-reduce%EF%BC%88%E6%B5%85%E6%8B%B7%E8%B4%9D%EF%BC%89"><span class="toc-text">6、Array.reduce（浅拷贝）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#7%E3%80%81Array-slice%EF%BC%88%E6%B5%85%E6%8B%B7%E8%B4%9D%EF%BC%89"><span class="toc-text">7、Array.slice（浅拷贝）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#8%E3%80%81JSON-parse-amp-JSON-stringify%EF%BC%88%E6%B7%B1%E6%8B%B7%E8%B4%9D%EF%BC%89"><span class="toc-text">8、JSON.parse &amp; JSON.stringify（深拷贝）</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%87%A0%E7%A7%8D%E7%89%B9%E6%AE%8A%E6%83%85%E5%86%B5"><span class="toc-text">几种特殊情况</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#9%E3%80%81Array-concat%EF%BC%88%E6%B5%85%E6%8B%B7%E8%B4%9D%EF%BC%89"><span class="toc-text">9、Array.concat（浅拷贝）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#10%E3%80%81Array-from%EF%BC%88%E6%B5%85%E6%8B%B7%E8%B4%9D%EF%BC%89"><span class="toc-text">10、Array.from（浅拷贝）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%B0%8F%E7%BB%93"><span class="toc-text">小结</span></a></li></ol></li></ol>
    
<style>
    .left-col .switch-btn,
    .left-col .switch-area {
        display: none;
    }
    .toc-level-3 i,
    .toc-level-3 ol {
        display: none !important;
    }
</style>
</div>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h1 id="JavaScript中十种一步拷贝数组的方法"><a href="#JavaScript中十种一步拷贝数组的方法" class="headerlink" title="JavaScript中十种一步拷贝数组的方法"></a>JavaScript中十种一步拷贝数组的方法</h1><p> <img src="/images/mianshi/array_copy.png"></p>
<p> JavaScript中我们经常会遇到拷贝数组的场景，但是都有哪些方式能够来实现呢，我们不妨来梳理一下</p>
<h2 id="1、扩展运算符（浅拷贝）"><a href="#1、扩展运算符（浅拷贝）" class="headerlink" title="1、扩展运算符（浅拷贝）"></a>1、扩展运算符（浅拷贝）</h2><p>自从ES6出现以来，这已经成为最流行的方法。它是一个很简单的语法，但是当你在使用类似于React和Redux这类库时，你会发现它是非常非常有用的。</p>
<pre><code class="bash">numbers = [1, 2, 3];
numbersCopy = [...numbers];</code></pre>
<blockquote>
<p>这个方法不能有效的拷贝多维数组。数组/对象值的拷贝是通过引用而不是值复制。</p>
</blockquote>
<pre><code class="bash">// 😊
numbersCopy.push(4);
console.log(numbers, numbersCopy);
// [1, 2, 3] and [1, 2, 3, 4]
// 只修改了我们希望修改的，原数组不受影响

// 😢
nestedNumbers = [[1], [2]];
numbersCopy = [...nestedNumbers];
numbersCopy[0].push(300);
console.log(nestedNumbers, numbersCopy);
// [[1, 300], [2]]
// [[1, 300], [2]]
// 由于公用引用，所以两个数组都被修改了，这是我们不希望的</code></pre>
<h2 id="2、for-循环（浅拷贝）"><a href="#2、for-循环（浅拷贝）" class="headerlink" title="2、for()循环（浅拷贝）"></a>2、for()循环（浅拷贝）</h2><p>考虑到函数式编程变得越来越流行，我认为这种方法可能是最不受欢迎的。</p>
<pre><code class="bash">numbers = [1, 2, 3];
numbersCopy = [];
for (i = 0; i &lt; numbers.length; i++) &#123;
  numbersCopy[i] = numbers[i];
&#125;</code></pre>
<blockquote>
<p>这个方法不能有效的拷贝多维数组。因为我们使用的是=运算符，它在处理数组/对象值的拷贝时通过引用而不是值复制。</p>
</blockquote>
<pre><code class="bash">// 😊
numbersCopy.push(4);
console.log(numbers, numbersCopy);
// [1, 2, 3] and [1, 2, 3, 4]

// 😢
nestedNumbers = [[1], [2]];
numbersCopy = [];
for (i = 0; i &lt; nestedNumbers.length; i++) &#123;
  numbersCopy[i] = nestedNumbers[i];
&#125;
numbersCopy[0].push(300);
console.log(nestedNumbers, numbersCopy);
// [[1, 300], [2]]
// [[1, 300], [2]]
// 由于公用引用，所以两个数组都被修改了，这是我们不希望的</code></pre>
<h2 id="3、while-循环（浅拷贝）"><a href="#3、while-循环（浅拷贝）" class="headerlink" title="3、while()循环（浅拷贝）"></a>3、while()循环（浅拷贝）</h2><p>和for() 类似。</p>
<pre><code class="bash">numbers = [1, 2, 3];
numbersCopy = [];
i = -1;
while (++i &lt; numbers.length) &#123;
  numbersCopy[i] = numbers[i];
&#125;</code></pre>
<h2 id="4、Array-map（浅拷贝）"><a href="#4、Array-map（浅拷贝）" class="headerlink" title="4、Array.map（浅拷贝）"></a>4、Array.map（浅拷贝）</h2><p>上面的for和while都是很“古老”的方式，让我们继续回到当前，我们会发现map方法。map源于数学，是将一个集合转换成另一种集合，同时保留结构的概念。</p>
<p>在英语中，它意味着Array.map 每次返回相同长度的数组。</p>
<pre><code class="bash">numbers = [1, 2, 3];
double = (x) =&gt; x * 2;

numbers.map(double);</code></pre>
<p>当我们使用map方法时，需要给出一个callback函数用于处理当前的数组，并返回一个新的数组元素。</p>
<p>和拷贝数组有什么关系呢？</p>
<p>当我们想要复制一个数组的时候，只需要在map的callback函数中直接返回原数组的元素即可。</p>
<pre><code class="bash">numbers = [1, 2, 3];
numbersCopy = numbers.map((x) =&gt; x);</code></pre>
<p>如果你想更数学化一点，(x) =&gt; x叫做恒等式。它返回给定的任何参数。</p>
<pre><code class="bash">identity = (x) =&gt; x;
numbers.map(identity);
// [1, 2, 3]</code></pre>
<blockquote>
<p>同样的，处理对象和数组的时候是引用而不是值复制。</p>
</blockquote>
<h2 id="5、Array-filter（浅拷贝）"><a href="#5、Array-filter（浅拷贝）" class="headerlink" title="5、Array.filter（浅拷贝）"></a>5、Array.filter（浅拷贝）</h2><p>Array.filter方法同样会返回一个新数组，但是并不一定是返回同样长度的，这和我们的过滤条件有关。</p>
<pre><code class="bash">[1, 2, 3].filter((x) =&gt; x % 2 === 0)
// [2]</code></pre>
<p>当我们的过滤条件总是true时，就可以用来实现拷贝。</p>
<pre><code class="bash">numbers = [1, 2, 3];
numbersCopy = numbers.filter(() =&gt; true);
// [1, 2, 3]</code></pre>
<blockquote>
<p>同样的，处理对象和数组的时候是引用而不是值复制。</p>
</blockquote>
<h2 id="6、Array-reduce（浅拷贝）"><a href="#6、Array-reduce（浅拷贝）" class="headerlink" title="6、Array.reduce（浅拷贝）"></a>6、Array.reduce（浅拷贝）</h2><p>其实用reduce来拷贝数组并没有展示出它的实际功能，但是我们还是要将其能够拷贝数组的能力说一下的</p>
<pre><code class="bash">numbers = [1, 2, 3];
numbersCopy = numbers.reduce((newArray, element) =&gt; &#123;
  newArray.push(element);
  return newArray;
&#125;, []);</code></pre>
<p>reduce() 方法对数组中的每个元素执行一个由您提供的reducer函数，将其结果汇总为单个返回值。</p>
<p>上面我们的例子中初始值是一个空数组，我们在遍历原数组的时候来填充这个空数组。该数组必须要从下一个迭代函数的执行后被返回出来。</p>
<blockquote>
<p>同样的，处理对象和数组的时候是引用而不是值复制。</p>
</blockquote>
<h2 id="7、Array-slice（浅拷贝）"><a href="#7、Array-slice（浅拷贝）" class="headerlink" title="7、Array.slice（浅拷贝）"></a>7、Array.slice（浅拷贝）</h2><p>slice 方法根据我们指定的start、end的index从原数组中返回一个浅拷贝的数组。</p>
<pre><code class="bash">[1, 2, 3, 4, 5].slice(0, 3);
// [1, 2, 3]
// Starts at index 0, stops at index 3

// 当不给定参数时，就返回了原数组的拷贝
numbers = [1, 2, 3, 4, 5];
numbersCopy = numbers.slice();
// [1, 2, 3, 4, 5]</code></pre>
<blockquote>
<p>同样的，处理对象和数组的时候是引用而不是值复制。</p>
</blockquote>
<h2 id="8、JSON-parse-amp-JSON-stringify（深拷贝）"><a href="#8、JSON-parse-amp-JSON-stringify（深拷贝）" class="headerlink" title="8、JSON.parse &amp; JSON.stringify（深拷贝）"></a>8、JSON.parse &amp; JSON.stringify（深拷贝）</h2><p>JSON.stringify将一个对象转成字符串；<br>JSON.parse将转成的字符串转回对象。</p>
<p>将它们组合起来可以将对象转换成字符串，然后反转这个过程来创建一个全新的数据结构。</p>
<pre><code class="bash">nestedNumbers = [[1], [2]];
numbersCopy = JSON.parse(
  JSON.stringify(nestedNumbers)
);
numbersCopy[0].push(300);
console.log(nestedNumbers, numbersCopy);
// [[1], [2]]
// [[1, 300], [2]]
// These two arrays are completely separate!</code></pre>
<blockquote>
<p>这个可以安全地拷贝深度嵌套的对象/数组</p>
</blockquote>
<h3 id="几种特殊情况"><a href="#几种特殊情况" class="headerlink" title="几种特殊情况"></a>几种特殊情况</h3><p>1、如果obj里面有时间对象，则JSON.stringify后再JSON.parse的结果，时间将只是字符串的形式。而不是时间对象；</p>
<pre><code class="bash">var test = &#123;
  name: &#39;a&#39;,
  date: [new Date(1536627600000), new Date(1540047600000)],
&#125;;

let b;
b = JSON.parse(JSON.stringify(test))
console.log(b)</code></pre>
<p>2、如果obj里有RegExp、Error对象，则序列化的结果将只得到空对象；</p>
<pre><code class="bash">const test = &#123;
  name: &#39;a&#39;,
  date: new RegExp(&#39;\\w+&#39;),
&#125;;
// debugger
const copyed = JSON.parse(JSON.stringify(test));
test.name = &#39;test&#39;
console.log(&#39;ddd&#39;, test, copyed)</code></pre>
<p>3、如果obj里有函数，undefined，则序列化的结果会把函数或 undefined丢失；</p>
<pre><code class="bash">const test = &#123;
  name: &#39;a&#39;,
  date: function hehe() &#123;
    console.log(&#39;fff&#39;)
  &#125;,
&#125;;
// debugger
const copyed = JSON.parse(JSON.stringify(test));
test.name = &#39;test&#39;
console.error(&#39;ddd&#39;, test, copyed)</code></pre>
<p>4、如果obj里有NaN、Infinity和-Infinity，则序列化的结果会变成null</p>
<p>5、JSON.stringify()只能序列化对象的可枚举的自有属性，例如 如果obj中的对象是有构造函数生成的， 则使用JSON.parse(JSON.stringify(obj))深拷贝后，会丢弃对象的constructor；</p>
<pre><code class="bash">function Person(name) &#123;
  this.name = name;
  console.log(name)
&#125;

const liai = new Person(&#39;liai&#39;);

const test = &#123;
  name: &#39;a&#39;,
  date: liai,
&#125;;
// debugger
const copyed = JSON.parse(JSON.stringify(test));
test.name = &#39;test&#39;
console.error(&#39;ddd&#39;, test, copyed)</code></pre>
<blockquote>
<p>参考文章：<a target="_blank" rel="noopener" href="https://www.jianshu.com/p/b084dfaad501">关于JSON.parse(JSON.stringify(obj))实现深拷贝应该注意的坑</a> </p>
</blockquote>
<h2 id="9、Array-concat（浅拷贝）"><a href="#9、Array-concat（浅拷贝）" class="headerlink" title="9、Array.concat（浅拷贝）"></a>9、Array.concat（浅拷贝）</h2><p>concat将数组与值或其他数组进行组合。</p>
<pre><code class="bash">[1, 2, 3].concat(4); // [1, 2, 3, 4]
[1, 2, 3].concat([4, 5]); // [1, 2, 3, 4, 5]</code></pre>
<p>如果我们不指定参数或者提供一个空数组作为参数，就可以进行浅拷贝。</p>
<pre><code class="bash">[1, 2, 3].concat(); // [1, 2, 3]
[1, 2, 3].concat([]); // [1, 2, 3]</code></pre>
<blockquote>
<p>同样的，处理对象和数组的时候是引用而不是值复制。</p>
</blockquote>
<h2 id="10、Array-from（浅拷贝）"><a href="#10、Array-from（浅拷贝）" class="headerlink" title="10、Array.from（浅拷贝）"></a>10、Array.from（浅拷贝）</h2><p>可以将任何可迭代对象转换为数组。给一个数组返回一个浅拷贝。</p>
<pre><code class="bash">console.log(Array.from(&#39;foo&#39;))
// [&#39;f&#39;, &#39;o&#39;, &#39;o&#39;]

numbers = [1, 2, 3];
numbersCopy = Array.from(numbers)
// [1, 2, 3]</code></pre>
<blockquote>
<p>同样的，处理对象和数组的时候是引用而不是值复制。</p>
</blockquote>
<h2 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h2><p>上面这些方法都是在使用一个步骤来进行拷贝。如果我们结合一些其他的方法或技术能够发现还有很多的方式来实现数组的拷贝，比如一系列的拷贝工具函数等。</p>

      
       <hr><span style="font-style: italic;color: gray;"> 转载请注明来源，欢迎对文章中的引用来源进行考证，欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论，也可以邮件至 jaytp@qq.com </span>
    </div>
</article>


<p>
    <a  class="dashang" onclick="dashangToggle()">赏</a>
</p>






    




    </div>
    <div class="copyright">
        <p class="footer-entry">
    ©2016-2020 Yelog
</p>
<p class="footer-entry">Built with <a href="https://hexo.io/" target="_blank">Hexo</a> and <a href="https://github.com/yelog/hexo-theme-3-hexo" target="_blank">3-hexo</a> theme</p>

    </div>
    <div class="full-toc">
        <button class="full" data-title="切换全屏 快捷键 s"><span class="min "></span></button>
<a class="" id="rocket" ></a>

    </div>
</div>

<div class="hide_box" onclick="dashangToggle()"></div>
<div class="shang_box">
    <a class="shang_close"  onclick="dashangToggle()">×</a>
    <div class="shang_tit">
        <p>喜欢就点赞,疼爱就打赏</p>
    </div>
    <div class="shang_payimg">
        <div class="pay_img">
            <img src="/img/alipay.jpg" class="alipay" title="扫码支持">
            <img src="/img/weixin.jpg" class="weixin" title="扫码支持">
        </div>
    </div>
    <div class="shang_payselect">
        <span><label><input type="radio" name="pay" checked value="alipay">支付宝</label></span><span><label><input type="radio" name="pay" value="weixin">微信</label></span>
    </div>
</div>


</body>
<script src="/js/jquery.pjax.js?v=1.1.0" ></script>

<script src="/js/script.js?v=1.1.0" ></script>
<script>
    var img_resize = 'default';
    function initArticle() {
        /*渲染对应的表格样式*/
        
            $("#post .pjax table").addClass("green_title");
        

        /*渲染打赏样式*/
        
        $("input[name=pay]").on("click", function () {
            if($("input[name=pay]:checked").val()=="weixin"){
                $(".shang_box .shang_payimg .pay_img").addClass("weixin_img");
            } else {
                $(".shang_box .shang_payimg .pay_img").removeClass("weixin_img");
            }
        })
        

        /*高亮代码块行号*/
        

        /*访问数量*/
        
        $.getScript("//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js");
        

        /*代码高亮，行号对齐*/
        $('.pre-numbering').css('line-height',$('.has-numbering').css('line-height'));

        
        
    }

    /*打赏页面隐藏与展示*/
    
    function dashangToggle() {
        $(".shang_box").fadeToggle();
        $(".hide_box").fadeToggle();
    }
    

</script>

<!--加入行号的高亮代码块样式-->

<!--自定义样式设置-->
<style>
    
    
    .nav {
        width: 542px;
    }
    .nav.fullscreen {
        margin-left: -542px;
    }
    .nav-left {
        width: 120px;
    }
    
    
    @media screen and (max-width: 1468px) {
        .nav {
            width: 492px;
        }
        .nav.fullscreen {
            margin-left: -492px;
        }
        .nav-left {
            width: 100px;
        }
    }
    
    
    @media screen and (max-width: 1024px) {
        .nav {
            width: 492px;
            margin-left: -492px
        }
        .nav.fullscreen {
            margin-left: 0;
        }
    }
    
    @media screen and (max-width: 426px) {
        .nav {
            width: 100%;
        }
        .nav-left {
            width: 100%;
        }
    }
    
    
    .nav-right .title-list nav a .post-title, .nav-right .title-list #local-search-result a .post-title {
        color: #383636;
    }
    
    
    .nav-right .title-list nav a .post-date, .nav-right .title-list #local-search-result a .post-date {
        color: #5e5e5f;
    }
    
    
    .nav-right nav a.hover, #local-search-result a.hover{
        background-color: #e2e0e0;
    }
    
    

    /*列表样式*/
    

    /* 背景图样式 */
    
    


    /*引用块样式*/
    

    /*文章列表背景图*/
    

    
</style>







</html>
